package com.example.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wemedia.controller.KafkaController;
import com.example.wemedia.dao.WmMaterialMapper;
import com.example.wemedia.dao.WmNewsMapper;
import com.example.wemedia.dao.WmNewsMaterialMapper;
import com.example.wemedia.dao.WmUserMapper;
import com.example.wemedia.feign.WmNewsEsFeign;
import com.example.wemedia.service.WmNewsService;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class WmNewsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private KafkaController kafkaController;
    @Autowired
    private WmNewsEsFeign wmNewsEsFeign;

    @Override
    public ResponseResult getAllList(WmNewsPageReqDto wmNewsPageReqDto) {
        if (wmNewsPageReqDto == null) {
            return ResponseResult.errorResult(404, "查询信息不能为空");
        }
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (wmNewsPageReqDto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        }
        if (wmNewsPageReqDto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, wmNewsPageReqDto.getStatus());
        }
        if (wmNewsPageReqDto.getKeyword() != null) {
            lambdaQueryWrapper.like(WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        }
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
        } else if (wmNewsPageReqDto.getEndPubDate() != null) {
            lambdaQueryWrapper.lt(WmNews::getPublishTime, wmNewsPageReqDto.getEndPubDate());
        } else if (wmNewsPageReqDto.getBeginPubDate() != null) {
            lambdaQueryWrapper.gt(WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate());
        }
        if (wmNewsPageReqDto.getSize()==0 || wmNewsPageReqDto.getSize()==null){
            wmNewsPageReqDto.setSize(5);
        }
        if (wmNewsPageReqDto.getPage()==0 || wmNewsPageReqDto.getPage()==null || wmNewsPageReqDto.getPage()>100){
            wmNewsPageReqDto.setPage(1);
        }
        Page<WmNews> wmNewsPage = new Page<>(wmNewsPageReqDto.getPage(),wmNewsPageReqDto.getSize());
        IPage<WmNews> wmNewsIPage = wmNewsMapper.selectPage(wmNewsPage, lambdaQueryWrapper);
        return ResponseResult.okResult(wmNewsIPage.getRecords());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addWmNews(WmNewsDto wmNewsDto) {
        if (wmNewsDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (wmNewsDto.getId()==null){
            WmNews wmNews = new WmNews();
            BeanUtils.copyProperties(wmNewsDto,wmNews);
            List<String> images = wmNewsDto.getImages();
            String s = "";
            List<String> imgList = new ArrayList<>();
            for (String image : images) {
                String img = StringUtils.substringPath(image);
                imgList.add(img);
                s +=img+",";
            }
            String newImgPath = "";
            if (!CollectionUtils.isEmpty(imgList)){
                newImgPath = s.substring(0, s.length() - 1);
            }
            log.info("截取后的图片为:{}",newImgPath);
            wmNews.setImages(newImgPath);
            wmNews.setCreatedTime(new Date());
            wmNews.setPublishTime(new Date());
            wmNews.setEnable(1);
            wmNews.setStatus(1);
            wmNewsMapper.insert(wmNews);
            /**
             * 查询包括前台的图片Url的数据
             */
            Integer wmnewsId = wmNews.getId();
            LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(WmMaterial::getUrl,imgList);
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper);
            /**
             * 批量添加
             */
            for (WmMaterial wmMaterial : wmMaterials) {
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setNewsId(wmnewsId);
                wmNewsMaterial.setMaterialId(wmMaterial.getId());
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            }
            kafkaController.getTopic(wmnewsId.toString());
            wmNewsEsFeign.addEsWmNews(wmNews);




            return ResponseResult.okResult(200,"添加成功");
        }else{
            List<String> getWmNews = wmNewsDto.getImages();
            List<String> imagesList = new ArrayList<>();
            for (String image : getWmNews) {
                String img = StringUtils.substringPath(image);
                imagesList.add(img);
            }
            LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(WmMaterial::getUrl,imagesList);
            List<WmMaterial> wmMaterials1 = wmMaterialMapper.selectList(queryWrapper);
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(WmNewsMaterial::getNewsId,wmNewsDto.getId());
            List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(queryWrapper1);
            if (wmNewsMaterials.size()!=0 && wmMaterials1.size()!=0){
                for (WmMaterial wmMaterial : wmMaterials1) {
                    for (WmNewsMaterial wmNewsMaterial : wmNewsMaterials) {
                        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(WmMaterial::getId,wmNewsMaterial.getMaterialId());
                        WmMaterial wmMaterial1 = wmMaterialMapper.selectOne(lambdaQueryWrapper);
                        if (wmMaterial.getId()!=wmMaterial1.getId()){
                            LambdaQueryWrapper<WmNewsMaterial> queryWrapper2 = new  LambdaQueryWrapper<WmNewsMaterial>();
                            queryWrapper2.eq(WmNewsMaterial::getNewsId,wmNewsDto.getId());
                            queryWrapper2.eq(WmNewsMaterial::getMaterialId,wmMaterial1.getId());
                            WmNewsMaterial wmNewsMaterial1 = wmNewsMaterialMapper.selectOne(queryWrapper2);
                            if (wmNewsMaterial1!=null){
                                wmMaterialMapper.deleteById(wmNewsMaterial.getMaterialId());
                            }
                        }
                        wmNewsMaterialMapper.deleteById(wmNewsMaterial.getId());
                    }
                }
            }
            WmNews wmNews = new WmNews();
            BeanUtils.copyProperties(wmNewsDto,wmNews);
            List<String> images = wmNewsDto.getImages();
            String s = "";
            List<String> imgList = new ArrayList<>();
            for (String image : images) {
                String img = StringUtils.substringPath(image);
                imgList.add(img);
                s +=img+",";
            }
            String newImgPath = "";
            if (!CollectionUtils.isEmpty(imgList)){
                newImgPath = s.substring(0, s.length() - 1);
            }
            log.info("截取后的图片为:{}",newImgPath);
            wmNews.setImages(newImgPath);
            wmNews.setCreatedTime(new Date());
            wmNews.setPublishTime(new Date());
            wmNews.setEnable(1);
            wmNews.setStatus(1);
            wmNewsMapper.updateById(wmNews);
            /**
             * 查询包括前台的图片Url的数据
             */
            Integer wmnewsId = wmNews.getId();
            LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.in(WmMaterial::getUrl,imgList);
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(lambdaQueryWrapper1);
            /**
             * 批量添加
             */
            for (WmMaterial wmMaterial : wmMaterials) {
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setNewsId(wmnewsId);
                wmNewsMaterial.setMaterialId(wmMaterial.getId());
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            }
            return ResponseResult.okResult(200,"修改成功");
        }
    }

    @Override
    public ResponseResult del(Integer id) {
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(WmNewsMaterial::getNewsId,id);
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(lambdaQueryWrapper);
        for (WmNewsMaterial wmNewsMaterial : wmNewsMaterials) {
            wmMaterialMapper.deleteById(wmNewsMaterial.getMaterialId());
            wmNewsMaterialMapper.deleteById(wmNewsMaterial.getId());
        }
        wmNewsMapper.deleteById(id);
        return ResponseResult.okResult(200,"删除成功");
    }

    @Override
    public WmNews getNewsById(Integer id) {
        return wmNewsMapper.selectById(id);
    }

    @Override
    public Integer updateWmNews(WmNews wmNews,Integer status) {
        wmNews.setStatus(status);
        return wmNewsMapper.updateById(wmNews);
    }

    @Override
    public List<WmNews> getCheckedWmnews() {
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getStatus,8).le(WmNews::getPublishTime,new Date());
        return wmNewsMapper.selectList(queryWrapper);
    }

    @Override
    public Integer updateWmNew(WmNews wmNews) {
        return wmNewsMapper.updateById(wmNews);
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public String selectName(Integer userId) {
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getId,userId);
        return wmUserMapper.selectOne(queryWrapper).getName();
    }
}
